package com.gxpt.app;

import android.Manifest;
import android.annotation.TargetApi;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.view.View;

import com.gxpt.app.view.Activity_home;
import com.gxpt.app.view.Activity_reg;
import com.tencent.android.tpush.XGIOperateCallback;
import com.tencent.android.tpush.XGPushConfig;
import com.tencent.android.tpush.XGPushManager;
import com.utils.logger.Logger;

import org.xutils.view.annotation.ContentView;
import org.xutils.view.annotation.Event;
import org.xutils.x;

import java.util.ArrayList;

@ContentView(R.layout.activity_main)
public class MainActivity extends Activity {

//    @ViewInject(R.id.button1)
//    Button button1;

    Context context;

    private final int SDK_PERMISSION_REQUEST = 127;
    private String permissionInfo;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        x.view().inject(this);
        XGPushConfig.enableDebug(this, true);//信鸽
        context = this;
//        initXG();
        getPersimmions();


    }

    @TargetApi(23)
    private void getPersimmions() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            ArrayList<String> permissions = new ArrayList<String>();
            /***
             * 定位权限为必须权限，用户如果禁止，则每次进入都会申请
             */
            // 定位精确位置
            if(checkSelfPermission(Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED){
                permissions.add(Manifest.permission.ACCESS_FINE_LOCATION);
            }
            if(checkSelfPermission(Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED){
                permissions.add(Manifest.permission.ACCESS_COARSE_LOCATION);
            }
			/*
			 * 读写权限和电话状态权限非必要权限(建议授予)只会申请一次，用户同意或者禁止，只会弹一次
			 */
            // 读写权限
            if (addPermission(permissions, Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
                permissionInfo += "Manifest.permission.WRITE_EXTERNAL_STORAGE Deny \n";
            }
            // 读取电话状态权限
            if (addPermission(permissions, Manifest.permission.READ_PHONE_STATE)) {
                permissionInfo += "Manifest.permission.READ_PHONE_STATE Deny \n";
            }

            if (permissions.size() > 0) {
                requestPermissions(permissions.toArray(new String[permissions.size()]), SDK_PERMISSION_REQUEST);
            }
        }
        ProgressAsyncTask asyncTask = new ProgressAsyncTask();
        asyncTask.execute(3000);
    }

    @TargetApi(23)
    private boolean addPermission(ArrayList<String> permissionsList, String permission) {
        if (checkSelfPermission(permission) != PackageManager.PERMISSION_GRANTED) { // 如果应用没有获得对应权限,则添加到列表中,准备批量申请
            if (shouldShowRequestPermissionRationale(permission)){
                return true;
            }else{
                permissionsList.add(permission);
                return false;
            }

        }else{
            return true;
        }
    }

    @TargetApi(23)
    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        // TODO Auto-generated method stub
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);

    }

    private void initXG(){
        // 1.获取设备Token
//        Handler handler = new HandlerExtension(MainActivity.this);
//        m = handler.obtainMessage();
        // 注册接口
        XGPushManager.registerPush(getApplicationContext(),
                new XGIOperateCallback() {
                    @Override
                    public void onSuccess(Object data, int flag) {
//                        Logger.w(
//                                "+++ register push sucess. token:" + data);
//                        m.obj = "+++ register push sucess. token:" + data;
//                        m.sendToTarget();

                        AppUtils.putXML_token(""+data,context);

//                        Logger.i("XML token = "+AppUtils.get_token(context));

                    }

                    @Override
                    public void onFail(Object data, int errCode, String msg) {
                        Logger.w(
                                "+++ register push fail. token:" + data
                                        + ", errCode:" + errCode + ",msg:"
                                        + msg);

//                        m.obj = "+++ register push fail. token:" + data
//                                + ", errCode:" + errCode + ",msg:" + msg;
//                        m.sendToTarget();

                    }
                });
    }



    @Event(value={R.id.button1,R.id.button2})
    private void getEvent(View view){
        Intent go = new Intent();
        switch(view.getId()){

            case R.id.button1:
                go.setClass(context,Activity_home.class);
                startActivity(go);
                break;
            case R.id.button2:
                go.setClass(context,Activity_reg.class);
                startActivity(go);
                break;
        }
    }

    public class ProgressAsyncTask extends AsyncTask<Integer, Integer, String> {

        @Override
        protected String doInBackground(Integer... params) {
            //记录版本
//            SPUtils.put(context,Constant.XML_device_ID, SysUtils.getDEVICE_ID(context));


            initXG();


            NetOperator netOperator = new NetOperator();
            netOperator.operator();
            return "jieshu";
        }

        @Override
        protected void onPostExecute(String result) {
            if(result.equals("jieshu")){

//                if(AppUtils.get_isFirst(context)){
//                    Intent toMain = new Intent();
////                toMain.setClass(context, aaaaa_index.class);
//                    toMain.setClass(context, GuideActivity.class);
//                    startActivity(toMain);
//                }else{



                    Intent toMain = new Intent();
                    toMain.setClass(context, Activity_home.class);
                    startActivity(toMain);
//                }


                finish();
            }
        }
    }

    public class NetOperator {

        public void operator(){
            try {
                //休眠1秒
                Thread.sleep(Constant.SPLASH_TIME);
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }

    }
}
